package com.spc.car.data.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spc.car.data.constant.UserConstants;
import com.spc.car.data.domain.TreeSelect;
import com.spc.car.data.domain.sys.TreeSysMenuNode;
import com.spc.car.data.domain.sys.vo.MetaVo;
import com.spc.car.data.domain.sys.vo.RouterVo;
import com.spc.car.data.entity.sys.SysMenu;
import com.spc.car.data.mapper.sys.SysMenuMapper;
import com.spc.car.data.service.sys.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spc.car.data.service.sys.SysRoleMenuService;
import com.spc.car.data.service.sys.SysRoleService;
import com.spc.car.data.service.sys.SysUserRoleService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-03-06
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;
    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(Long userId)
    {
        return selectMenuList(new SysMenu(), userId);
    }

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId)
    {
        List<SysMenu> menuList = null;
        QueryWrapper condition = new QueryWrapper<SysMenu>()
                .eq(StringUtils.isNotBlank(menu.getVisible()), "visible", menu.getVisible())
                .like(StringUtils.isNotBlank(menu.getMenuName()), "menu_name", menu.getMenuName());

        // 管理员显示所有菜单信息
        if (userId != null && sysUserRoleService.CheckAdminByUserId(userId)) {
            menuList = list(condition);
        }
        else {
            condition.eq("ur.user_id", userId);
            menuList = baseMapper.selectMenuListByUserId(condition);
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId)
    {
        List<String> perms = baseMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<TreeSysMenuNode> selectMenuTreeByUserId(Long userId)
    {
        List<SysMenu> menuAll = null;
        QueryWrapper condition = new QueryWrapper<SysMenu>();
        // 管理员显示所有菜单信息
        if (userId != null && sysUserRoleService.CheckAdminByUserId(userId)) {
            menuAll = list(condition);
        }
        else {
            condition.eq("ur.user_id", userId);
            condition.eq("visible", UserConstants.MENU_DISPLAY);
            menuAll = baseMapper.selectMenuListByUserId(condition);
        }
        List<TreeSysMenuNode> menus = toTreeNode(menuAll);
        return getChildPerms(menus, 0);
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    public List<Integer> selectMenuListByRoleId(Long roleId)
    {
        return baseMapper.selectMenuListByRoleId(roleId);
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<TreeSysMenuNode> menus)
    {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (TreeSysMenuNode menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setName(StringUtils.capitalize(menu.getPath()));
            router.setPath(getRouterPath(menu));
            router.setComponent(StringUtils.isEmpty(menu.getComponent()) ? "Layout" : menu.getComponent());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getMenuType()));
            List<TreeSysMenuNode> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && ("M".equals(menu.getMenuType()) || "S".equals(menu.getMenuType())))
            /*if (!cMenus.isEmpty() && cMenus.size() > 0)*/
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<TreeSysMenuNode> buildMenuTree(List<TreeSysMenuNode> menus)
    {
        List<TreeSysMenuNode> returnList = new ArrayList<>();
        for (Iterator<TreeSysMenuNode> iterator = menus.iterator(); iterator.hasNext();)
        {
            TreeSysMenuNode t = (TreeSysMenuNode) iterator.next();
            // 根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == 0)
            {
                recursionFn(menus, t);
                returnList.add(t);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<TreeSysMenuNode> menus)
    {
        List<TreeSysMenuNode> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public SysMenu selectMenuById(Long menuId)
    {
        return getById(menuId);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(Long menuId)
    {
        int result = count(new QueryWrapper<SysMenu>().eq("parent_id",menuId));
        return result > 0 ? true : false;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean checkMenuExistRole(Long menuId)
    {
        int result = sysRoleMenuService.checkMenuExistRole(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(SysMenu menu)
    {
        return baseMapper.insert(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(SysMenu menu)
    {
        return baseMapper.updateById(menu);
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId)
    {
        return baseMapper.deleteById(menuId);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(SysMenu menu)
    {
        Long menuId = Objects.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu info = getOne(new QueryWrapper<SysMenu>().eq("menu_name",menu.getMenuName())
                .eq("parent_id", menu.getParentId()));
        if (!Objects.isNull(info) && info.getMenuId().longValue() != menuId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu)
    {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录
        if (0 == menu.getParentId() && "1".equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        return routerPath;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<TreeSysMenuNode> getChildPerms(List<TreeSysMenuNode> list, int parentId)
    {
        List<TreeSysMenuNode> returnList = new ArrayList<>();
        for (Iterator<TreeSysMenuNode> iterator = list.iterator(); iterator.hasNext();)
        {
            TreeSysMenuNode t = (TreeSysMenuNode) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<TreeSysMenuNode> list, TreeSysMenuNode t)
    {
        // 得到子节点列表
        List<TreeSysMenuNode> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TreeSysMenuNode tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                // 判断是否有子节点
                Iterator<TreeSysMenuNode> it = childList.iterator();
                while (it.hasNext())
                {
                    TreeSysMenuNode n = (TreeSysMenuNode) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<TreeSysMenuNode> getChildList(List<TreeSysMenuNode> list, TreeSysMenuNode t)
    {
        List<TreeSysMenuNode> tlist = new ArrayList<>();
        Iterator<TreeSysMenuNode> it = list.iterator();
        while (it.hasNext())
        {
            TreeSysMenuNode n = (TreeSysMenuNode) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<TreeSysMenuNode> list, TreeSysMenuNode t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    List<TreeSysMenuNode> toTreeNode(List<SysMenu> menus) {
        List<TreeSysMenuNode> listTreeSysMenuNode = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(menus)) {
            menus.stream().forEach(a -> {
                TreeSysMenuNode treeSysMenuNode = new TreeSysMenuNode();
                BeanUtils.copyProperties(a, treeSysMenuNode);
                listTreeSysMenuNode.add(treeSysMenuNode);
            });
        }
        return listTreeSysMenuNode;
    }

}
